<?php
namespace app\console\behavior;
use think\facade\Request;
use think\Model;

class ParentStr
{
    private $controller = null;
    private $class = null;
    private $model = null;

    public function __construct()
    {
        $this->controller = Request::controller(true);
        $this->class = '\app\model\\'.Request::controller();
        $this->model = new $this->class;
    }
    public function before_write($data)
    {

        if(!empty($data->parent_id)){ //parent_id>0
            $sql_count = $this->model->where('id', $data->parent_id)->value('count'); //当前上级表里的级别
            $sql_parent_str = $this->model->where('id', $data->parent_id)->value('parent_str'); //当前上级的分类串(不包含自己)
            if ($data->parent_id == 0) { //如果parent_id是顶级 就是第一个级
                $count = 1;
                $parent_str = 0;
            } else { //如果不是顶级 就得去表里查看这个parent_id层级是多少
                $count = 1 + $sql_count;
                $parent_str = $sql_parent_str . ',' . $data->parent_id;
            }
            $data->count = $count;

            $data->parent_str = $parent_str; //当前级的上级实际parent_str
            if (request()->action() == 'update') {
                $tree_list = getMenuTree($this->model->select(), $data->id); //已经是下级的分类列
                if (!empty($tree_list)) { //所有下级count和parent_str
                    foreach ($tree_list as $k => $v) {
                        $this->model->where('id', $v['id'])->update(['count' => $count + $v['level']]);
                        $this->model->where('id', $v['id'])->update(['parent_str' => $parent_str . $v['current_parent_str']]);
                    }

                }

            }
        }else{ //SQLSTATE[HY000]: General error: 1364 Field 'count' doesn't have a default value
            $data->count = 1;
            $data->parent_str = 0;

        }


    }




}